<template>
	<app-page>
		<wd-config-provider :theme="theme">
			<view class="container">
				<!-- 订单信息页面 -->
				<view class="order-info">
					<view class="order-info-header">
						<view class="title">{{ orderInfo.anjian_name }}</view>
						<view class="user-info">
							<view class="user">
								<view class="img">
									<image :src="orderInfo.head" mode="aspectFill"></image>
								</view>
								<view class="name text-ellipsis">
									{{ orderInfo.nickname }}
								</view>
							</view>
							<view class="date">
								<text class="iconfont icon-shijian"></text>
								{{ orderInfo.create_time }}
							</view>
						</view>
					</view>
					<view class="order-info-body">
						<view v-for="(item,index) in infoFields">
							<view class="item">
								<view class="item-label">
									{{ item.field_comment }}
								</view>
								<view class="item-value">
									<template
										v-if="item.field_type === 'Textarea' || item.field_type === 'Picker' || item.field_type === 'Input'">
										{{ item.value }}
									</template>
									<template v-if="item.field_type === 'City'">
										{{ item.value }}
									</template>
									<template v-if="item.field_type === 'File'">
										<upload v-model="item.value" not-upload not-card padding=""></upload>
									</template>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 待服务  -->
				<view class="btns" v-if="orderInfo.status_title === '待接单'">
					<wd-button type="success"
						custom-class="wd-button-custom-class-my-cancel square wd-button-custom-class-w100"
						@click="doRefuse">拒绝接单</wd-button>
					<wd-button type="success"
						custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100"
						@click="doAgree">确认接单</wd-button>
				</view>
				<!-- 服务中  -->
				<view class="card tool" v-if="orderInfo.status_title === '服务中'">
					<view class="item" @click="goImGroup">
						<view class="icon">
							<image src="@/order/static/img/image-and-text.png"></image>
						</view>
						<text>图文联系</text>
					</view>
					<view class="item" @click="goPage('/collaborative/release/release',{
						anjian_order_id: orderInfo.id,
					})">
						<view class="icon">
							<image src="@/order/static/img/coordination.png"></image>
						</view>
						<text>协同办理</text>
					</view>
					<view class="item" @click="callPhone">
						<view class="icon">
							<image src="@/order/static/img/phone.png"></image>
						</view>
						<text>电话联系</text>
					</view>
					<view class="item" @click="goPage('/query/release/release',{
						anjian_order_id: orderInfo.id,
					})">
						<view class="icon">
							<image src="@/order/static/img/release.png"></image>
						</view>
						<text>发布查询</text>
					</view>

					<view class="item" @click="goPage('/tools/tips/tips')">
						<view class="icon">
							<image src="@/order/static/img/remind.png"></image>
						</view>
						<text>设置提醒</text>
					</view>
					<view class="item" @click="goPage('/tools/remark/remark')">
						<view class="icon">
							<image src="@/order/static/img/memo.png"></image>
						</view>
						<text>备忘录</text>
					</view>
					<view class="item" @click="goPage()">
						<view class="icon">
							<image src="@/order/static/img/coordination.png"></image>
						</view>
						<text>讼前调解</text>
					</view>
					<view class="item" @click="goPage('/tools/index/index')">
						<view class="icon">
							<image src="@/order/static/img/more.png"></image>
						</view>
						<text>更多</text>
					</view>
				</view>
				<view class="btns" v-if="orderInfo.status_title === '服务中'">
					<wd-button type="success"
						custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100"
						@click="complete">完成案件</wd-button>
				</view>
			</view>
		</wd-config-provider>
		<wd-popup safe-area-inset-bottom custom-class="wd-popup-order" v-model="showOrder" position="bottom"
			@close="setOrderShow">
			<view class="body">
				<view class="title">
					接单信息
				</view>
				<wd-form ref="form">
					<wd-cell-group border>
						<wd-picker @confirm="pickerConfirm" ref="wdPicker" prop="category_id"
							:column-change="columnChange" v-model="order.category_id" label-width="100px"
							:columns="caseTypeList" value-key="id" label-key="title" label="案件类型" placeholder="请选择案件类型">

						</wd-picker>
						<wd-input v-model="order.price" label="费用" label-width="100px" prop="price" clearable
							placeholder="请输入费用" />
						<wd-cell vertical title-width="100px" title="备注信息">
							<wd-textarea v-model="order.f_desc" prop="f_desc" on-border auto-height placeholder="备注信息"
								clearable />
						</wd-cell>

					</wd-cell-group>
					<view class="footer">
						<wd-button custom-class="wd-button-custom-class-my-success wd-button-custom-class-w100"
							type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
					</view>
				</wd-form>
			</view>
		</wd-popup>
	</app-page>

</template>

<script lang="ts">
	import { defineComponent, ref, computed } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';

	import useRouter from '@/hooks/useRouter.ts';
	import {
		queryCaseOrderInfo, doCaseDenyOrder, getCategoryTwoList, getCategoryFirstList, doCaseReceiveOrder,
		doCaseFinishOrder, getUseryPhone
	} from "@/api/index"
	import { useImStore, useUserStore } from '../../store';
	export default defineComponent({
		name: '',
		setup(props, ctx) {
			const orderInfo = ref({
				anjian_name: "",

			});
			const fieldsValue = ref([]);
			const router = useRouter();
			const imStore = useImStore();
			const userStore = useUserStore();
			// 是否打开创建订单
			const showOrder = ref<boolean>(false);

			const order = ref<any>({
				firstCategory: null,
				twoCategory: null,
				category_id: null,
				price: "", // 费用
				f_desc: "", // 备注信息，可不填，用于备注订单信息，如：订单包含xxx商品，不含xxx商品等。
			});
			const caseTypeList = ref([]);
			// 日间light、夜间dark主题
			const theme = ref('light');
			const initCategory = (res : any, func ?: Function) => {
				getCategoryTwoList({
					id: res[0].id
				}).then(res => {
					if (func) {
						func(res);
					} else {
						order.value.twoCategory = res[0].id;
						order.value.category_id = [order.value.firstCategory, order.value.twoCategory];
						order.value[1] = res;
					}


				});
			}
			const pickerConfirm = (e : any) => {
				console.log(e, 'e');
				if (e.length > 1) {
					order.value.category_id = e;
				} else {
					order.value.category_id = [order.value.order, order.value.twoCategory];
				}

			}
			const columnChange = (e) => {
				const valuse = e.getValues();
				if (valuse[0] !== order.value.firstCategory) {
					initCategory([{
						id: valuse[0],
					}], (list) => {
						if (list.length > 0) {
							e.setColumnData(1, list, 0)
						} else {
							e.setColumnData(1, [e.getSelects()[0]], 0)
							order.value.twoCategory = e.getSelects()[0].id;
						}
					})
				}
				order.value.firstCategory = valuse[0]; // 获取一级分类的值，并将其赋值给orderInfo.firstCategory。
				order.value.twoCategory = valuse[1]; // 获取二级分类的值，并将其赋值给orderInfo.twoCategory。
			}
			const handleSubmit = () => {
				doCaseReceiveOrder({
					anjian_order_id: orderInfo.value.id,
					...order.value,
				}).then(res => {
					uni.$wdToast.show("接单成功！")
					setTimeout(() => {
						router.switchTab("/pages/order/order")
					}, 1000)
				});
			}
			// 拒绝接单操作
			const doRefuse = () => {
				uni.$wdToast.confirm("确认拒绝当前案件吗？", "提示").then((res : any) => {
					doCaseDenyOrder({
						anjian_order_id: orderInfo.value.id,
					}).then((res : any) => {
						uni.$wdToast.show("拒绝成功！")
						setTimeout(() => {
							router.switchTab("/pages/order/order")
						}, 1000)
					})
				});

			};
			// 确认接单操作
			const doAgree = () => {
				uni.$wdToast.confirm("确认接手当前案件吗？", "提示").then((res : any) => {
					showOrder.value = !showOrder.value;
				});
			};
			// 完成案件
			const complete = () => {
				uni.$wdToast.confirm("确认完成当前案件吗？", "提示").then((res : any) => {
					doCaseFinishOrder({
						anjian_order_id: orderInfo.value.id,
					}).then(res => {
						uni.$wdToast.show("当前案件已完成！")
						setTimeout(() => {
							router.switchTab("/pages/order/order")
						}, 1000)
					});

				});

			};
			const goImGroup = async () => {
				// const memberList = [
				// 	{ userID: orderInfo.value.uuid },
				// 	{ userID: userStore.uuid },
				// ]
				// await imStore.createGroup(orderInfo.value.order_sn, orderInfo.value.anjian_name, memberList)
				// await imStore.toGroupChat(orderInfo.value.order_sn);
				imStore.switchConversation('C2C' + orderInfo.value.uuid)
				router.push({
					url: "/im/chat/chat",
					params: {
						uuid: orderInfo.value.uuid
					}
				});
			}


			const callPhone = () => {
				uni.$wdToast.confirm("点击确认后当前会拨打对方电话，请先确认对方是否方便接听", "提示").then((res) => {
					getUseryPhone({
						uuid: orderInfo.value.uuid
					}).then(res => {
						// console.log(res)
						uni.makePhoneCall({
							phoneNumber: res.phone,
							success: () => {

							}
						});
					});
				});
			}
			const getFieldsValue = () => {
				const temp = JSON.parse(JSON.stringify(orderInfo.value)); // 深拷贝，避免修改原始数据
				for (let key in temp) {
					if (key.indexOf('f_') !== -1) {
						fieldsValue.value.push(temp[key])
					}
				}
			};
			const goPage = (url : any, params ?: any) => {
				if (!url) {
					uni.$wdToast.error("暂未开放")
					return;
				}
				router.push({
					url,
					params
				})
			}
			const infoFields = computed(() => {
				const temp = JSON.parse(JSON.stringify(orderInfo.value)); // 深拷贝，避免影响原始数据。
				const exd_fields = [...JSON.parse(orderInfo.value.exd_fields_wt) || '[]', ...JSON.parse(orderInfo.value.exd_fields_save || '[]')]; // 转换为数组。
				let list = [];
				let keys = Object.keys(temp);
				if (exd_fields.length <= 0) {
					return list;
				}
				for (var i = 0; i < keys.length; i++) {
					let field = exd_fields.find((item : any) => item['field_name'] == keys[i])
					if (keys[i].indexOf("f_") !== -1 && temp[keys[i]] && keys[i] !== 'f_address_title' && field) {
						let d = {
							value: temp[keys[i]],
							...field
						}
						console.log(d);
						if (field.field_type === 'City' && temp.f_address_title) {
							d.value = temp?.f_address_title
						}

						list.push(d)
					}
				}
				return list;
			})
			onLoad((options) => {
				console.log(options); // 打印options参数
				queryCaseOrderInfo({
					anjian_order_id: options.id
				}).then((res : any) => {
					console.log(res);
					orderInfo.value = res;
					// infoFields.value = [...JSON.parse(res.exd_fields_wt), ...JSON.parse(res.exd_fields_save || '[]')];
					// console.log("infoFields", infoFields);
					getFieldsValue();
				});
				// 获取案件分类
				getCategoryFirstList().then((res : any) => {
					caseTypeList.value[0] = res;
					order.value.firstCategory = res[0].id;
					initCategory(res);
				})
				// orderInfo.status = Number(options.status); // 获取订单状态
			});
			return {
				theme,
				getFieldsValue,
				fieldsValue,
				infoFields,
				doRefuse,
				doAgree,
				orderInfo,
				complete,
				showOrder,
				order,
				caseTypeList,
				initCategory,
				pickerConfirm,
				columnChange,
				handleSubmit,
				callPhone,
				goPage,
				goImGroup
			};
		}
	});
</script>
<!-- #ifdef MP-WEIXIN -->
<style lang="less">
	page {
		background-color: #f2f2f2;
	}
</style>
<!-- #endif -->
<style lang="less" scoped>
	page {
		background-color: #f2f2f2;
	}

	.wd-popup-order {

		.body {
			padding: 24rpx;

			.wd-cell__value {
				.wd-textarea::after {
					display: none;
				}
			}

		}

		.title {
			font-size: 40rpx;
			font-weight: bold;
			text-align: center;
			padding-bottom: 24rpx;
		}

		.footer {
			margin-top: 24rpx;
		}
	}

	.container {
		padding: 27rpx;

		.order-info {
			width: 100%;
			background: #ffffff;
			box-shadow: 0rpx 2rpx 42rpx 0rpx rgba(0, 0, 0, 0.06);
			border-radius: 13rpx;
			margin: 0 auto;

			&-header {
				background: #fafafa;
				border-radius: 13rpx;
				padding: 30rpx;

				.title {
					font-family: PingFang;
					font-weight: 500;
					font-size: 33rpx;
					color: #000000;
				}

				.user-info {
					border-top: 2rpx solid #bfbfbf;
					padding-top: 17rpx;
					margin-top: 27rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.user {
						display: flex;
						align-items: center;
						width: 56%;

						.img {
							width: 64.79rpx;
							height: 64.79rpx;
							border-radius: 50%;
							overflow: hidden;
							margin-right: 10rpx;

							image {
								width: 100%;
								height: 100%;
							}
						}

						.name {
							font-family: PingFang;
							font-weight: 400;
							font-size: 25rpx;
							color: #000000;
							margin-left: 12rpx;
						}
					}

					.date {
						font-family: PingFang;
						font-weight: 400;
						font-size: 25rpx;
						color: #000000;

						.iconfont {
							color: #9f9f9f;
						}
					}
				}
			}

			&-body {
				padding: 30rpx;
				font-family: PingFang;
				font-weight: 400;
				font-size: 22rpx;
				color: #000000;
				line-height: 47rpx;
			}
		}

		.btns {
			display: flex;
			justify-content: space-between;
			margin-top: 34rpx;
			width: 100%;

			:deep(.square) {
				width: 30% !important;
				margin: 0;
			}

			:deep(.square+.square) {
				width: 50% !important;
			}
		}

		.tool {
			margin-top: 34rpx;
			padding: 25rpx;
			width: calc(100% - 50rpx);
			display: flex;
			align-items: center;
			flex-wrap: wrap;

			.item {
				width: calc(100% / 4);
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;

				.icon {
					width: 76rpx;
					height: 76rpx;
					background: #eeeeee;
					border-radius: 50%;
					overflow: hidden;
					margin-bottom: 18rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					image {
						width: 100%;
						height: 100%;
					}
				}

				text {
					font-family: PingFang;
					font-weight: 400;
					font-size: 22rpx;
					color: #000000;
				}
			}

			.item:nth-child(5),
			.item:nth-child(6),
			.item:nth-child(7),
			.item:nth-child(8) {
				margin-top: 30rpx;
			}

			.item:nth-child(1) {

				// 第一个图标样式设置
				.icon image {
					width: 31.94rpx;
					height: 28.47rpx;
				}
			}

			.item:nth-child(2) {

				// 第一个图标样式设置
				.icon image {
					width: 31.94rpx;
					height: 30.56rpx;
				}
			}

			.item:nth-child(3) {

				// 第一个图标样式设置
				.icon image {
					width: 31.25rpx;
					height: 31.25rpx;
				}
			}

			.item:nth-child(4) {

				// 第一个图标样式设置
				.icon image {
					width: 38.19rpx;
					height: 27.78rpx;
				}
			}

			.item:nth-child(5) {

				// 第一个图标样式设置
				.icon image {
					width: 32.64rpx;
					height: 34.72rpx;
				}
			}

			.item:nth-child(6) {

				// 第一个图标样式设置
				.icon image {
					width: 26.39rpx;
					height: 27.78rpx;
				}
			}

			.item:nth-child(7) {

				// 第一个图标样式设置
				.icon image {
					width: 29.86rpx;
					height: 30.56rpx;
				}
			}

			.item:nth-child(8) {

				// 第一个图标样式设置
				.icon image {
					width: 33.33rpx;
					height: 33.33rpx;
				}
			}
		}

		.tool+.btns {
			:deep(.square) {
				width: 100% !important;
			}
		}
	}
</style>